package com.yangzb.ppt;
import org.apache.poi.sl.usermodel.PlaceableShape;
import org.apache.poi.sl.usermodel.Placeholder;
import org.apache.poi.xslf.usermodel.*;
import org.apache.xmlbeans.XmlObject;

import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class CopySlideDemo {
    public static void main(String[] args) throws Exception {
        // 打开现有的PowerPoint文件
        InputStream inputStream = new FileInputStream("original.pptx");
        XMLSlideShow pptOriginal = new XMLSlideShow(inputStream);

        // 创建一个新的空白幻灯片集
        XMLSlideShow pptCopy = new XMLSlideShow();

        // 假设我们要复制第一个幻灯片
        XSLFSlide slideToCopy = pptOriginal.getSlides().get(0);

        // 复制幻灯片
        XSLFSlide newSlide = pptCopy.createSlide();
        copySlideContent(slideToCopy, newSlide);

        // 保存复制的幻灯片到新的文件
        OutputStream outputStream = new FileOutputStream("copy.pptx");
        pptCopy.write(outputStream);

        // 关闭流
        inputStream.close();
        outputStream.close();

        System.out.println("幻灯片已复制并保存。");
    }

    public static void copySlideContent(XSLFSlide sourceSlide, XSLFSlide targetSlide) {
        // 复制幻灯片上的所有形状
        List<XSLFShape> shapes = sourceSlide.getShapes();
        Dimension sourcePageSize = sourceSlide.getSlideShow().getPageSize();
        Dimension targetPageSize = targetSlide.getSlideShow().getPageSize();


        for (XSLFShape shape : shapes) {
            if(shape instanceof PlaceableShape&&!Placeholder.TITLE.equals(shape.getPlaceholder())){
                Rectangle2D anchor = shape.getAnchor();
                double x = anchor.getX();
                double y = anchor.getY();
                if(targetPageSize.getHeight()>sourcePageSize.getHeight()){
                    y = (targetPageSize.getHeight()-sourcePageSize.getHeight())/2 +y;
                }
                if(targetPageSize.getWidth()>sourcePageSize.getWidth()){
                    x = (targetPageSize.getWidth()-sourcePageSize.getWidth())/2+x;
                }
                anchor.setRect(x,y,anchor.getWidth(),anchor.getHeight());
                ((PlaceableShape) shape).setAnchor(anchor);
            }else {
                System.out.println(shape);
            }

            targetSlide.importContent(shape.getSheet());
        }

        // 如果需要，还可以复制幻灯片的其他属性，如背景等
    }
}
